<template>
    <div>
        <el-dialog :title="info.isAdd ? '商品添加' : '商品编辑'" :visible.sync="info.isshow" @closed="closed" @opened="opened">
            <div>form:{{ form }}</div>
            <el-form :model="form">
                <!-- 一级分类 -->
                <el-form-item label="一级分类" :label-width="formLabelWidth">
                    <el-select v-model="form.first_cateid" placeholder="请选择" @change="changeFirtCateId">
                        <!-- 遍历list -->
                        <el-option v-for="item in list" :key="item.id" :label="item.catename" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 二级分类 -->
                <el-form-item label="二级分类" :label-width="formLabelWidth">
                    <el-select v-model="form.second_cateid" placeholder="请选择">
                        <!-- 遍历list -->
                        <el-option v-for="item in secondCateList" :key="item.id" :label="item.catename"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 商品名称 -->
                <el-form-item label="商品名称" :label-width="formLabelWidth">
                    <el-input v-model="form.goodsname" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 价格 -->
                <el-form-item label="价格" :label-width="formLabelWidth">
                    <el-input v-model="form.price" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 市场价格 -->
                <el-form-item label="市场价格" :label-width="formLabelWidth">
                    <el-input v-model="form.market_price" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 图片 -->
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <!-- 上传文件 -->
                    <div class="my-upload">
                        <h3 class="plus">+</h3>
                        <input v-if="info.isshow" class="ipt" type="file" @change="changeFile" />
                        <img v-if="imgUrl" :src="imgUrl" alt />
                    </div>
                </el-form-item>

                <!-- 商品规格 -->
                <el-form-item label="商品规格" :label-width="formLabelWidth">
                    <el-select v-model="form.specsid" placeholder="请选择" @change="changeSpecsId">
                        <!-- 遍历list -->
                        <el-option v-for="item in specsList" :key="item.id" :label="item.specsname" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 规格属性 -->
                <el-form-item label="规格属性" :label-width="formLabelWidth">
                    <el-select v-model="form.specsattr" placeholder="请选择商品属性" multiple>
                        <!-- 遍历list -->
                        <el-option v-for="item in arr" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 是否新品 -->
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio v-model="form.isnew" :label="1">是</el-radio>
                    <el-radio v-model="form.isnew" :label="2">否</el-radio>
                </el-form-item>

                <!-- 是否热卖 -->
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="form.ishot" :label="1">是</el-radio>
                    <el-radio v-model="form.ishot" :label="2">否</el-radio>
                </el-form-item>

                <!-- 状态 -->
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
                </el-form-item>

                <!-- 商品描述 -->
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="editor" v-if="info.isshow"></div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" v-if="info.isAdd" @click="add">添加</el-button>
                <el-button type="primary" v-else @click="edit">修改</el-button>
            </div>
        </el-dialog>  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { reqgoodsadd, reqgoodsinfo, reqgoodsedit, reqcatelist, } from "../../../http/api"
import { errorAlert, successAlert } from "../../../utils/alert"
import path from "path";
import E from "wangeditor";

export default {
    props: ["info"],
    data() {
        return {
            formLabelWidth: "120px",
            form: {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: null,
                description: "",
                specsid: "",
                specsattr: [],
                isnew: 1,
                ishot: 1,
                status: 1,
            },
            //二级分类展示列表
            secondCateList: [],
            //规格属性
            arr: [],
            imgUrl: "",
        }
    },
    computed: {
        ...mapGetters({
            list: "cate/list",
            //商品规格
            specsList: "specs/list"
        }),
    },
    mounted() {
        //请求一级分类列表
        this.reqList();
        //请求商品规格列表
        this.reqspecslist(true)

    },
    methods: {
        ...mapActions({
            reqList: "cate/reqList",
            //商品规格
            reqspecslist: "specs/reqList",
            reqTotal: 'goods/reqTotal',//请求总数
            reqgoodsList: "goods/reqList",
        }),

        //打开动画结束时的回调
        opened() {
            //弹框出现完成
            //创建编辑器
            this.editor = new E("#editor");
            this.editor.create();
            this.editor.txt.html(this.form.description)
        },

        checkDate() {
            return new Promise((resolve, rejeck) => {
                if (this.form.pid === "") {
                    errorAlert("上级分类不能为空")
                    return;
                }
                if (this.form.catename === "") {
                    errorAlert("分类名称不能为空")
                    return
                }
                if (this.form.img === null) {
                    errorAlert("请上传图片")
                    return
                }
                resolve();
            })
        },

        //选了文件
        changeFile(e) {
            let file = e.target.files[0]
            //判断它的后缀名
            let imgArr = [".jpg", ".jpeg", ".png", ".gif"]
            let extname = path.extname(file.name)
            if (!imgArr.includes(extname)) {
                errorAlert("请上传正确的图片")
                return;
            }
            //判断大小
            if (file.size > 2 * 1024 * 1024) {
                errorAlert("最大支持2M")
                return;
            }
            //根据文件生成一个地址
            this.imgUrl = URL.createObjectURL(file)
            //将文件赋值给form.img
            this.form.img = file
        },
        //清空表单的数据
        empty() {
            this.form = {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: null,
                description: "",
                specsid: "",
                specsattr: [],
                isnew: 1,
                ishot: 1,
                status: 1,
            },
                //二级分类展示列表
                this.secondCateList = [],
                //规格属性
                this.arr = [],
                this.imgUrl = ""
        },
        //点了添加
        add() {
            //添加验证先
            this.checkDate().then(() => {
                reqgoodsadd({
                    ...this.form,
                    specsattr: this.form.specsattr.join(","),
                    // 商品描述
                    description: this.editor.txt.html(),
                }).then(res => {
                    if (res.data.code == 200) {
                        //弹窗成功
                        successAlert(res.data.msg);
                        //调用empty清空表单内容
                        this.empty();
                        //关闭弹框
                        this.info.isshow = false;
                        //刷新列表
                        this.reqgoodsList()
                        // // 请求总数
                        this.reqTotal();
                    }
                })
            })
        },
        //点了取消
        cancel() {
            this.info.isshow = false
        },
        //编辑渲染页面
        getOne(id) {
            reqgoodsinfo({ id: id }).then(res => {
                if (res.data.code == 200) {
                    //赋值给form
                    this.form = res.data.list
                    //给图片赋值
                    this.imgUrl = this.$pre + this.form.img
                    //添加id
                    this.form.id = id
                    //根据一级分类id请求二级分类
                    this.getSecondList()
                    //规格属性
                    this.form.specsattr = this.form.specsattr.split(",")

                    //计算规格属性列表
                    this.getArr()
                    //给编辑器赋值
                    // if (this.editor) {
                    //     this.editor.txt.html(this.form.description)
                    // }
                }
            })
        },
        //修改
        edit() {
            this.checkDate().then(() => {
                reqgoodsedit({
                    ...this.form,
                    specsattr: this.form.specsattr.join(","),
                    // 商品描述
                    description: this.editor.txt.html(),
                }).then(res => {
                    if (res.data.code == 200) {
                        //成功弹窗
                        successAlert(res.data.msg);
                        //清除数据表单
                        this.empty();
                        //关闭窗口
                        this.info.isshow = false
                        //刷新页面
                        this.reqgoodsList()
                    }
                })
            })
        },
        //弹框关闭
        closed() {
            if (this.info.isAdd == false) {
                this.empty()
                //清空imgUrl
                this.imgUrl = ""
            }
            if (this.info.isAdd) {
                this.form.description = this.editor.txt.html();
            }
        },
        //修改了一级分类
        changeFirtCateId() {
            //清空二级分类的值
            this.form.second_cateid = ""
            //在根据一级分类的id查找二级分类
            this.getSecondList();
        },
        //根据一级分类，获取二级分类的列表
        async getSecondList() {
            let res = await reqcatelist({ pid: this.form.first_cateid })
            if (res.data.code == 200) {
                //把获取到的值赋值给当前secondCateList二级列表中
                this.secondCateList = res.data.list
            }
        },
        //修改商品规格获取规格属性
        changeSpecsId() {
            //清空规格属性列表
            this.form.specsattr = ""
            //根据当前specsid值与那个id一样
            this.getArr();
        },
        //根据当前specsid值判断与listid是否一致
        getArr() {
            let obj = this.specsList.find((item) => item.id == this.form.specsid)
            this.arr = obj ? obj.attrs : []
        },

    },
}
</script>
<style scoped lang="less">
@import "../../../less/index.less";

.my-upload {
    width: 100px;
    height: 100px;
    border: 1px dotted @primary;
    border-radius: 3%;
    position: relative;

    .plus {
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 100px;
    }

    .ipt {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        opacity: 0;
        z-index: 10;
        cursor: pointer;
    }

    img {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 9;
    }
}
</style>